package com.ljx.funchat.chat.dao;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ljx.funchat.chat.domain.entity.Contact;
import com.ljx.funchat.chat.mapper.ContactMapper;
import com.ljx.funchat.chat.service.IContactService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljx.funchat.common.domain.vo.req.CursorPageBaseReq;
import com.ljx.funchat.common.domain.vo.resp.CursorPageBaseResp;
import com.ljx.funchat.common.utils.CursorUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 会话表 服务实现类
 * </p>
 *
 * @author LiJunXi
 * @since 2024-02-14
 */
@Service
public class ContactDao extends ServiceImpl<ContactMapper, Contact> {

    public CursorPageBaseResp<Contact> getContactPage(Long uid, CursorPageBaseReq request) {
        return CursorUtils.getCursorPageByMysql(this, request, wrapper -> {
            wrapper.eq(Contact::getUid, uid);
        }, Contact::getActiveTime);
    }

    public List<Contact> getByRoomIds(List<Long> roomIds, Long uid) {
        return lambdaQuery().eq(Contact::getUid, uid)
                .in(Contact::getRoomId, roomIds)
                .list();
    }

    public void refreshMsg(Long roomId, List<Long> memberIds, Long msgId, Date activeTime) {
        this.baseMapper.refreshMsgOrCreate(roomId, memberIds, msgId, activeTime);
    }

    public Contact getByRoomId(Long roomId, Long uid) {
        List<Contact> contactList = this.getByRoomIds(Arrays.asList(roomId), uid);
        if (contactList.size() == 1){
            return contactList.get(0);
        } else {
            return null;
        }
    }

    public void deleteContact(List<Long> ids, Long roomId) {
        this.baseMapper.delete(new LambdaQueryWrapper<Contact>()
                        .eq(Contact::getRoomId, roomId)
                        .in(Contact::getUid, ids));
    }
}
